//
//  MyStudyAndCollectionViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "MyStudyAndCollectionViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "LinLi.h"
#import "StudyAndCollection.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "BookDetailVC.h"
#import "MediaDetailVC.h"
#import "NewDetailController.h"
#import "TongZhiDetailViewController.h"
#import "ZhiShiDetailViewController.h"

@interface MyStudyAndCollectionViewController ()

@end

@implementation MyStudyAndCollectionViewController{
    
    float screenWidth;
    float screenHeight;
    NSMutableArray *studyListArray;
    int contentPage;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title=self.navTitle;
    screenWidth=[UIScreen mainScreen].bounds.size.width;
    screenHeight=[UIScreen mainScreen].bounds.size.height;
    
    [self createNavBtn];
    [self createTableView];
    [self addRefreshAttribute];
    
    contentPage=1;
    studyListArray=[[NSMutableArray alloc]init];
    [self getStudyWithType:self.type andPage:1 andIsRefresh:YES];
}

-(void)createTableView{
    
    self.myStudyTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-64) style:UITableViewStyleGrouped];
    self.myStudyTableView.dataSource=self;
    self.myStudyTableView.delegate=self;
    self.myStudyTableView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.myStudyTableView];
}

-(void)createNavBtn{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    studyListArray=[[NSMutableArray alloc]init];
//    [self getStudyWithType:self.type andPage:1];
    [self addRefreshAttribute];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
    [self.myStudyTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    [self.myStudyTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

- (void)reloadDataToNew:(BOOL)new{
    
    if (new) {
        contentPage=1;
        [self getStudyWithType:self.type andPage:1 andIsRefresh:YES];
    }else{
        contentPage=contentPage+1;
        [self getStudyWithType:self.type andPage:contentPage andIsRefresh:NO];
    }
}

-(void)getStudyWithType:(int)type andPage:(int)page andIsRefresh:(BOOL)isRefresh{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    NSString *url=@"favorite.php";
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",type] forKey:@"type"];//1.收藏2.学习
    [CheckParams setObject:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [CheckParams setObject:@"10" forKey:@"pagesize"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:url httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [self.myStudyTableView.legendHeader endRefreshing];
        [self.myStudyTableView.legendFooter endRefreshing];
        
        if (![[result objectForKey:@"response"] isEqualToString:@"favorite"]) {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"获取详情失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }
        
        NSArray *listArray=[result objectForKey:@"list"];
        
        if (listArray.count==0) {
            
            if (!isRefresh) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"没有更多内容了!";
                [hud hide:YES afterDelay:1];
                contentPage=contentPage-1;
            }
            [self.myStudyTableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            return ;
        }
        
        if (isRefresh) {
            [studyListArray removeAllObjects];
        }
        for (NSDictionary *dic in listArray) {
            
            //StudyAndCollection *study=[[StudyAndCollection alloc]initWithDictionary:dic];
            StudyAndCollection *study=[StudyAndCollection yy_modelWithDictionary:dic];
            [studyListArray addObject:study];
        }
        [self.myStudyTableView reloadData];
        
    }failureAction:^{
        
    }];
}

-(void)goBack{
    
    self.tabBarController.tabBar.hidden=NO;
    [self.navigationController popViewControllerAnimated:YES];
}

//<<<<<<< HEAD
////-(void)viewWillAppear:(BOOL)animated{
////
////    self.tabBarController.tabBar.hidden=YES;
////
////}
//
//=======
//>>>>>>> 14692e8f36eb8309c9f7f0f263d37f2cf550851e
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return studyListArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if(!cell){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    StudyAndCollection *study=[studyListArray objectAtIndex:indexPath.row];
    
    UIImageView *headImg=[[UIImageView alloc] init];
    [headImg setContentMode:UIViewContentModeScaleAspectFill];
    headImg.clipsToBounds = YES;
    headImg.frame=CGRectMake(10, 10, 50, 50);
    [headImg setImageWithURL:[NSURL URLWithString:study.pic] placeholderImage:[UIImage imageNamed:@"phoneplace.png"]];
    [cell addSubview:headImg];
    
    UILabel *titleLab=[[UILabel alloc]initWithFrame:CGRectMake(65, 10, screenWidth-75, 20)];
    titleLab.text=study.title;
    [cell addSubview:titleLab];
    
    UILabel *authorLab=[[UILabel alloc]initWithFrame:CGRectMake(65, 30, 200, 15)];
    authorLab.text=[NSString stringWithFormat:@"作者:%@",study.au_or_sper];
    authorLab.textColor=[UIColor grayColor];
    authorLab.font=[UIFont systemFontOfSize:13];
    [cell addSubview:authorLab];
    
    UILabel *introduceLab=[[UILabel alloc]initWithFrame:CGRectMake(65, 45, screenWidth-75, 15)];
    introduceLab.text=[NSString stringWithFormat:@"%@",study.introduce];
    introduceLab.textColor=[UIColor grayColor];
    introduceLab.font=[UIFont systemFontOfSize:13];
    [cell addSubview:introduceLab];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    StudyAndCollection *study=[studyListArray objectAtIndex:indexPath.row];
    if (self.type==2) {
        //学习
        if (study.type==0) {
            //文章
            BookDetailVC *bookVC=[[BookDetailVC alloc]init];
            bookVC.bookID=[NSString stringWithFormat:@"%d",study.itemid];
            [self.navigationController pushViewController:bookVC animated:YES];
        }else{
            //音频视频
            MediaDetailVC *mediaVC=[[MediaDetailVC alloc]init];
            mediaVC.mediaID=[NSString stringWithFormat:@"%d",study.itemid];
            [self.navigationController pushViewController:mediaVC animated:YES];
        }
    }else{
        
        switch (study.type) {
            case 0:{
                
                NewDetailController *newVC=[[NewDetailController alloc]init];
                newVC.itemID=[NSString stringWithFormat:@"%d",study.itemid];
                [self.navigationController pushViewController:newVC animated:YES];
            }
                break;
            case 1:{
                
                TongZhiDetailViewController *tongZhiVC=[[TongZhiDetailViewController alloc]init];
                tongZhiVC.itemid=study.itemid;
                tongZhiVC.type=1;
                [self.navigationController pushViewController:tongZhiVC animated:YES];
            }
                break;
            case 2:{
                
                TongZhiDetailViewController *tongZhiVC=[[TongZhiDetailViewController alloc]init];
                tongZhiVC.itemid=study.itemid;
                tongZhiVC.type=2;
                [self.navigationController pushViewController:tongZhiVC animated:YES];
            }
                break;
            case 3:{
                
                ZhiShiDetailViewController *zhiShiVC=[[ZhiShiDetailViewController alloc]init];
                zhiShiVC.itemid=study.itemid;
                zhiShiVC.item_mid=study.item_mid;
                [self.navigationController pushViewController:zhiShiVC animated:YES];
            }
                break;
            default:
                break;
        }
        
    }
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //删除学习和收藏
    StudyAndCollection *study=[studyListArray objectAtIndex:indexPath.row];
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[NSString stringWithFormat:@"%d",study.id] forKey:@"id"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"del_favorite.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
        if (str) {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"删除失败!";
            [hud hide:YES afterDelay:1];
            return ;
        }else{
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"删除成功!";
            [hud hide:YES afterDelay:1];
            [studyListArray removeAllObjects];
            [self.myStudyTableView reloadData];
            contentPage=1;
            [self getStudyWithType:self.type andPage:1 andIsRefresh:YES];
        }
        
    }failureAction:^{
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
